import bcrypt from 'bcryptjs'
import jwt from 'jsonwebtoken'
import db from '../config/database.js'
import {jwtConfig} from '../config/jwt.js'
import {isValidPhone} from '../utils/helpers.js'

// 注册
export async function register(req, res) {
  try {
    const {phone, password, email} = req.body

    // 验证必填字段
    if (!phone || !password) {
      return res.status(400).json({
        success: false,
        error: '手机号和密码不能为空'
      })
    }

    // 验证手机号格式
    if (!isValidPhone(phone)) {
      return res.status(400).json({
        success: false,
        error: '手机号格式不正确'
      })
    }

    // 检查手机号是否已注册
    const [existingUsers] = await db.query('SELECT id FROM users WHERE phone = ?', [phone])

    if (existingUsers.length > 0) {
      return res.status(400).json({
        success: false,
        error: '该手机号已注册'
      })
    }

    // 加密密码
    const hashedPassword = await bcrypt.hash(password, 10)

    // 插入用户
    const [result] = await db.query(
      'INSERT INTO users (phone, password, email, created_at) VALUES (?, ?, ?, NOW())',
      [phone, hashedPassword, email || null]
    )

    // 生成 JWT token
    const token = jwt.sign(
      {
        id: result.insertId,
        phone: phone
      },
      jwtConfig.secret,
      {expiresIn: jwtConfig.expiresIn}
    )

    res.status(201).json({
      success: true,
      data: {
        token,
        user: {
          id: result.insertId,
          phone: phone,
          email: email || null
        }
      }
    })
  } catch (error) {
    console.error('注册错误:', error)
    res.status(500).json({
      success: false,
      error: '注册失败，请稍后重试'
    })
  }
}

// 登录
export async function login(req, res) {
  try {
    const {phone, password} = req.body

    // 验证必填字段
    if (!phone || !password) {
      return res.status(400).json({
        success: false,
        error: '手机号和密码不能为空'
      })
    }

    // 查询用户
    const [users] = await db.query('SELECT * FROM users WHERE phone = ?', [phone])

    if (users.length === 0) {
      return res.status(401).json({
        success: false,
        error: '手机号或密码错误'
      })
    }

    const user = users[0]

    // 验证密码
    const isPasswordValid = await bcrypt.compare(password, user.password)

    if (!isPasswordValid) {
      return res.status(401).json({
        success: false,
        error: '手机号或密码错误'
      })
    }

    // 生成 JWT token
    const token = jwt.sign(
      {
        id: user.id,
        phone: user.phone
      },
      jwtConfig.secret,
      {expiresIn: jwtConfig.expiresIn}
    )

    res.json({
      success: true,
      data: {
        token,
        user: {
          id: user.id,
          phone: user.phone,
          email: user.email
        }
      }
    })
  } catch (error) {
    console.error('登录错误:', error)
    res.status(500).json({
      success: false,
      error: '登录失败，请稍后重试'
    })
  }
}

// 获取当前用户信息
export async function getCurrentUser(req, res) {
  try {
    const userId = req.user.id

    const [users] = await db.query('SELECT id, phone, email, created_at FROM users WHERE id = ?', [
      userId
    ])

    if (users.length === 0) {
      return res.status(404).json({
        success: false,
        error: '用户不存在'
      })
    }

    res.json({
      success: true,
      data: users[0]
    })
  } catch (error) {
    console.error('获取用户信息错误:', error)
    res.status(500).json({
      success: false,
      error: '获取用户信息失败'
    })
  }
}
